<template>
    <div>
        <Search @search="onSearch" @reset="onReset" />
        <TreeTableHeder :isParentDisabled="isParentDisabled" @add="addHandle" />
        <TreeTable
            ref="TreeTableRef"
            v-loading="Data.loading"
            :draggable="draggable"
            :allow-drop="allowDrop"
            :props="treeProps"
            node-key="id"
            lazy
            :load="loadNode"
            @node-expand="nodeExpandHandle"
            @node-drop="handleDrop"
            @add="addChildHandle"
            @edit="editHandle"
            @delete="deleteHandle" />
        <Pagination
            :total="Data.totalCount"
            :page-size="searchParams.perPage"
            :current-page="searchParams.page"
            @size-change="onSizeChange"
            @pageChange="onPageChange" />
        <AddDia ref="AddDiaRef" :data="Data" @success="successHandle" />
    </div>
</template>
<script setup>
import Search from './search.vue';
import TreeTableHeder from './treeTableHeder.vue';
import TreeTable from './treeTable.vue';
import Pagination from '@/components/Pagination.vue';
import AddDia from './addDia.vue';

import storage from '@/commons/storage';
import store from '@/store/index';
import request from '@/request';
import { getGoodsCategoryListHook, getGoodsCategoryChildListHook } from '@/hooks/goods';

import { ElMessage } from 'element-plus';
import { ref, reactive, computed } from 'vue';

// 一级分组最大新增数量 100
const isParentDisabled = computed(() => {
    return Data.totalCount >= 100;
});

const draggable = computed(() => {
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'classify:draggable';
    if (!permissions.has(code)) {
        return false;
    } else {
        return true;
    }
});
const TreeTableRef = ref(null);
const Data = reactive({
    shopId: storage.get('ZW-SHOPID'),
    loading: false,
    type: '', // 操作类型
    level: 1, // 操作层级
    tableData: [],
    totalCount: 0
});
const searchParams = reactive({
    categoryName: '',
    page: 1,
    perPage: 10
});
const treeProps = {
    label: 'name',
    children: 'children',
    isLeaf: 'hasChildren' // 是否有子节点
};
/* ------------------------------------------------ 获取列表数据 start ------------------------------------------------ */
const childRequestSuccess = {};
let nodeHad = null;
let resolveHad = null;
let currentData = null;
const loadNode = async (node = nodeHad, resolve = resolveHad) => {
    if (node.level === 0) {
        nodeHad = node;
        resolveHad = resolve;
        Data.loading = true;
        const data = await getGoodsCategoryListHook(searchParams);
        Data.loading = false;
        Data.totalCount = data.totalCount || 0;
        node.childNodes = [];
        resolve(data.list);
        return;
    }
    const id = node.data.id;
    const childList = await getGoodsCategoryChildListHook(id);
    childRequestSuccess[id] = childList[0].id;
    resolve(childList);
};
const onSearch = v => {
    Object.assign(searchParams, v);
    loadNode();
};
const onReset = v => {
    Object.assign(searchParams, v);
    loadNode();
};

const onSizeChange = v => {
    searchParams.page = 1;
    searchParams.perPage = v;
    loadNode();
};
const onPageChange = v => {
    searchParams.page = v;
    loadNode();
};

// 展开-子节点接口请求失败再次展开重新请求
const nodeExpandHandle = (data, node) => {
    if (childRequestSuccess[data.id]) return;
    node.loaded = false;
    node.expand();
};
/* ------------------------------------------------ 获取列表数据 end ------------------------------------------------ */

const successHandle = () => {
    Data.type === 'add' ? addSuccess() : editSuccess();
};

/* ------------------------------------------------ 新增 start ------------------------------------------------ */
const AddDiaRef = ref(null);
const addHandle = () => {
    Data.level = 0;
    Data.type = 'add';
    AddDiaRef.value.openDialog({ id: '', level: 1, type: 'add' });
};
const addChildHandle = ({ data, node }) => {
    Data.type = 'add';
    Data.level = 1;
    currentData = data;
    AddDiaRef.value.openDialog({ id: data.id, level: 2, type: 'add' });
};
const addSuccess = async () => {
    // 一级分类
    if (Data.level === 0) {
        loadNode();
        return;
    }
    // 二级分类
    if (Data.level === 1 && currentData.hasChildren) {
        // 新增子分类当前无子级，刷新父级列表
        loadNode();
    } else {
        const typeId = currentData.id;
        const list = await getGoodsCategoryChildListHook(typeId);
        TreeTableRef.value.$refs.treeRef.updateKeyChildren(typeId, list);
    }
};
/* ------------------------------------------------ 新增 end ------------------------------------------------ */

/* ------------------------------------------------ 编辑 start ------------------------------------------------ */
const editSuccess = async () => {
    if (Data.level === 1) {
        loadNode();
        return;
    }
    if (Data.level === 2) {
        const typeId = currentData.parentId;
        const list = await getGoodsCategoryChildListHook(typeId);
        TreeTableRef.value.$refs.treeRef.updateKeyChildren(typeId, list);
    }
};

const editHandle = ({ node, data }) => {
    Data.level = node.level;
    Data.type = 'edit';
    currentData = data;
    let { categoryName, parentId, id, level } = data;
    AddDiaRef.value.openDialog({ data, id, level, parentId, categoryName, type: 'edit' });
};
/* ------------------------------------------------ 编辑 end ------------------------------------------------ */

/* ------------------------------------------------ 删除 start ------------------------------------------------ */
const deleteHandle = async ({ node, data }) => {
    let params = { shopId: Data.shopId, categoryId: data.id };
    await request('delCategoryServ', params);
    ElMessage.success('删除成功');
    if (node.level === 1) {
        if (searchParams.page > 1 && Data.totalCount % searchParams.perPage === 1) searchParams.page--;
        loadNode();
        return;
    }
    TreeTableRef.value.$refs.treeRef.remove(node);
};
/* ------------------------------------------------ 删除 end ------------------------------------------------ */

/* ------------------------------------------------ 拖拽排序 start ------------------------------------------------ */
const handleDrop = (before, after, inner, event) => {
    const params = {
        shopId: Data.shopId,
        category: []
    };
    params.category = after.parent.childNodes.map((el, index) => {
        return { id: el.data.id, cateSort: index + 1 };
    });
    request('dragCategoryServ', params);
};
/* ------------------------------------------------ 拖拽排序 end ------------------------------------------------ */

const allowDrop = (draggingNode, dropNode, type) => {
    if (draggingNode.data.level === dropNode.data.level) {
        //parentId 是父节点id
        if (draggingNode.data.parentId === dropNode.data.parentId) {
            return type === 'prev' || type === 'next';
        } else {
            return false;
        }
    } else {
        // 不同级进行处理
        return false;
    }
};
</script>
